<template>
<div>


<!--  搜索框-->
  <div>

    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="搜索商品">
        <el-input v-model="searchForm.searchKey" placeholder="请输入商品名称"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
      <el-button type="success" @click="toAdd">添加商品</el-button>
    </el-form>
  </div>
  <el-row>
    <el-col :span="4" v-for="(goods, index) in tableData" :key="goods.id" :offset="index > 0 ? 1 : 0">
      <el-card :body-style="{ padding: '10px' }">
        <img :src=goods.goodsImg class="image">
        <div style="padding: 14px;">
          <span>{{ goods.goodsName }}</span><br>
          <div style="padding-top: 5px">
            <span>商品库存:{{goods.goodsNum}}</span>
          </div>

          <div class="bottom clearfix">
            <span style="color: red">¥{{goods.goodsPrice}}</span><br>
            <div style="padding-top: 5px"><el-button @click="addCart(goods)" size="small" type="danger">加入购物车</el-button></div>

          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>
  <div>
<!-- 分页   -->
    <div class="block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pageNum"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total,sizes, prev, pager, next,jumper"
          :total="totalCount">
      </el-pagination>
    </div>
  </div>
<!--添加的对话框表单-->
  <div>
    <el-dialog title="商品添加" :visible.sync="dialogFormVisible">
      <el-form :model="goodsForm">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.goodsName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="商品价格" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.goodsPrice" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="商品数量" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.goodsNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" :label-width="formLabelWidth">

          <el-upload
              class="avatar-uploader"
              action="http://localhost:8083/goods/uploadImg"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="goodsForm.goodsImg" :src="goodsForm.goodsImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品分类" :label-width="formLabelWidth">
          <div class="block">
            <el-cascader
                v-model="goodsForm.categoryId"
                :options="options"
                :props="{ expandTrigger: 'hover',value:'id',label:'name' }"
                @change="handleChange"></el-cascader>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addGoods">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</div>
</template>


<script>
export default {
  data() {
    return {
      options: [],
      defaultCheck: [],
      gridData: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      goodsForm: {
        goodsName: '',
        goodsNum: '',
        goodsPrice: '',
        goodsImg: '',
        categoryId: []
      },
      formLabelWidth: '120px',
      tableData:[],
      pageNum: 1,
      pageSize:4,
      pageSizes:[1,4,10,15],
      totalCount:0,
      searchForm: {
        searchKey: ''
      }
    };
  },
  methods:{
    addCart(goods){
      // localStorage.getItem("userId")
      //加入购物车,发送后台请求保存相关数据
      this.axios.get("http://localhost:8083/goods/addCart?goodsId="+goods.id).then(resp=>{
        if(resp.data=="success"){
          alert("加入购物车成功!")
        }else {
          alert("加入失败,请联系管理员!")
        }
      })

    },
    handleAvatarSuccess(res, file) {
      this.goodsForm.goodsImg = res;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    getCategorysTrees() {
      this.axios.get("http://127.0.0.1:8083/goods/categorys").then(resp=>{
        this.options=resp.data
      })
    },
    //三级联动的方法
    handleChange(categoryIds) {
      //选中的分类id,赋值给form表单
      this.goodsForm.categoryId=categoryIds
    },
    //提交表单
    addGoods(){
    var newCateIdsStr = this.goodsForm.categoryId.join(",");
      //1.提交表单
      this.axios.post("http://localhost:8083/goods/save",this.goodsForm).then(resp=>{
        if(resp.data=="success"){
          alert("添加成功")
          this.initGoodsData();//重新刷新当前页面
        }
      })
      //2.关闭对话框
      this.dialogFormVisible=false
    },
    //跳到商品添加页
    toAdd(){
      this.getCategorysTrees();
      this.dialogFormVisible=true//显示对话框
    },
    //提交搜索框的表单
    onSubmit() {
      this.initGoodsData();
    },
    handleSizeChange(val) {
      this.pageSize=val
      this.initGoodsData();
    },
    handleCurrentChange(val) {
      this.pageNum=val;
      this.initGoodsData();
    },
    initGoodsData(){
      this.axios.post("http://localhost:8083/goods/goodsList?pageNum="+this.pageNum+"&pageSize="+this.pageSize+"&searchKey="+this.searchForm.searchKey).then(resp=>{
        this.tableData=resp.data.records
        this.totalCount=resp.data.total
        this.pageSize=resp.data.size
        this.pageNum=resp.data.current
      })
    }
  },
  mounted() {
    this.initGoodsData();
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}
</style>
